package com.common.common;

import android.os.Build;
import android.text.TextUtils;

import com.common.common.utils.AppUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CommonInterceptor implements Interceptor {
    private String mImei = "";

    public CommonInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody requestBody = request.body();
        FormBody.Builder builder = new FormBody.Builder();
        if (Build.VERSION.SDK_INT >= 29) {
            mImei = AppUtils.getImeiForQ();
        }
        if (TextUtils.isEmpty(mImei)) {
            mImei = AppUtils.getImei();
        }
        if (!TextUtils.isEmpty(mImei)) {
            builder.addEncoded("imei", mImei);
        }
        builder.addEncoded("appOs", "android");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.CHINA);// HH:mm:ss
        //获取当前时间
        builder.addEncoded("timestamp", simpleDateFormat.format(new Date(System.currentTimeMillis())));
        if (requestBody instanceof FormBody) {
            FormBody formBody = (FormBody) requestBody;
            for (int i = 0; i < formBody.size(); i++) {    // 如果要对已有的参数做进一步处理可以这样拿到参数
                builder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
            }
            request = request.newBuilder().post(builder.build()).build();  //重新构建
        } else {
            request = request.newBuilder().method(request.method(), requestBody).post(builder.build()).build();  //重新构建
        }
        return chain.proceed(request);
    }
}